<template>
<div>
  <Breadcrumb icon="icon-experiment" :items="['实验室', '聊天室']" />
  <a-card class="general-card" title="聊天室">
    <div class="divider-demo">
      <a-scrollbar ref="scrollbar" type="track" style="height:300px; overflow: auto;">
      <div class="message-list">
        <div v-for="msg in msgs" :key="msg" class="flex-box" >
          <div class="content" :class="{'mine-box': msg?.fromId === username}">
            <a-typography-title :heading="6">{{ msg?.fromId }}</a-typography-title>
            <span style="background-color: var(--color-fill-1); padding: 10px; border-radius: 10px;">
                  {{msg?.content}}
                </span>
          </div>
        </div>
      </div>
      </a-scrollbar>
      <a-divider class="half-divider" />
      <div style="text-align: right">
        <a-textarea v-model="msgContent" placeholder="Please enter something" allow-clear/>
        <a-button @click="sendMsg">发送</a-button>
      </div>
    </div>
    <div style="width: 200px; height: 50px; position: absolute; top: 65px; right: 20px">
      <a-form-item label="用户名">
        <a-select v-model="destId" placeholder="输入用户名" allow-create @change="onChange"/>
      </a-form-item>
    </div>
  </a-card>
</div>
</template>

<script setup>
import { onBeforeUnmount, onMounted, ref} from 'vue';
import SockJS from  'sockjs-client/dist/sockjs.min';
import Stomp from 'stompjs';
import { getToken } from "@/utils/auth";
import { useUserStore } from '@/store';
import { Message } from '@arco-design/web-vue';
import { send, unread, read } from "@/api/modules/laboratory/message";

const { username } = useUserStore()
const msgs = ref([])

let stomp

const destId = ref('')
const msgContent = ref('')

const scrollbar = ref(null)

const sendMsg = async () => {
  if (msgContent.value === '') {
    return
  }
  const messageDto = {
    fromId: username,
    destId,
    chatType: 'p2p',
    msgType: 'txt',
    content: msgContent.value
  }
  await send(destId.value, messageDto)
  msgs.value.push(messageDto)
  msgContent.value = ''
  scrollbar.value?.scrollTop(68 * msgs.value.length)
}

const onChange = async () => {
  msgs.value = (await unread(destId.value)).data
  await read(destId.value)
}

onMounted(async () => {
  const token = getToken();
  const socket = new SockJS(`${import.meta.env.VITE_API_BASE_URL}/message/messaging?access_token=${token}`);
  stomp = Stomp.over(socket)
  await stomp.connect({}, () => {
    stomp.subscribe(`/user/${username}/messages`, (res) => {
      const ret = JSON.parse(res.body);
      msgs.value.push(ret)
      Message.info({
        content: `${ret?.fromId}发来一条消息`,
        duration: 5000,
      })
    })
  }, () => {
    Message.error({
      content: '连接失败',
      duration: 3000,
    })
  })
})

onBeforeUnmount(() => {
  stomp.disconnect()
})
</script>

<script>
export default {
  name: 'Message'
}
</script>

<style scoped>
.divider-demo {
  box-sizing: border-box;
  width: 700px;
  height: 500px;
  padding: 24px;
  border: 15px solid rgb(var(--gray-2));

}

.half-divider {
  width: calc(100% - 55px);
  min-width: auto;
  margin: 16px 0;
}
.flex-box {
  display: flex;
  align-items: center;
  justify-content: center;
}

.flex-box .content {
  flex: 1;
  color: var(--color-text-2);
  font-size: 12px;
  line-height: 20px;
  padding: 0 20px;
}
.mine-box {
  text-align: right;
}
</style>
